//
//  PhotoBrowserViewController.swift
//  HMWeibo
//
//  Created by wulei on 15/12/19.
//  Copyright © 2015年 wulei. All rights reserved.
//

import UIKit
import SVProgressHUD
/// 可重用 Cell 标识符
private let PhotoBrowserViewCellId = "PhotoBrowserViewCellId"
class PhotoBrowserViewController: UIViewController {
// 定义数组
    private var urls: [NSURL]
    private var currentIndexPath: NSIndexPath
    
    // MARK: - 实现按钮的监听方法
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    @objc private func  save() {

        // 拿到cell
        let cell = collectionView.visibleCells()[0] as! PhotoBrowserCell
        guard let image = cell.imageView.image else{
            return
        }
        // 保存图片
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
        
        
        
    }
    
    //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject?){
        let message = (error == nil) ? "保存成功" : "保存失败"
        SVProgressHUD.showInfoWithStatus(message)
    }
    
    
    // 构造函数
    init(urls: [NSURL],indexPath: NSIndexPath){
        self.urls = urls
        self.currentIndexPath = indexPath
        
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func loadView() {
        
        var rect = UIScreen.mainScreen().bounds
        rect.size.width += 20
        view = UIView(frame: rect)
        
//        view = UIView()
        
        setupUI()
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        collectionView.scrollToItemAtIndexPath(currentIndexPath, atScrollPosition: .CenteredHorizontally, animated: true)

    }
    
    // 懒加控件
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: PhotoBrowserViewLayout())
    private lazy var closeButton: UIButton = UIButton(title: "关闭", fontSize: 14, color: UIColor.whiteColor(), imageName: nil, backColor: UIColor.darkGrayColor())
    private lazy var saveButton: UIButton = UIButton(title: "保存", fontSize: 14, color: UIColor.whiteColor(), imageName: nil, backColor: UIColor.darkGrayColor())
    
    
    private class PhotoBrowserViewLayout: UICollectionViewFlowLayout {
        override func prepareLayout() {
            itemSize = collectionView!.bounds.size
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            scrollDirection = .Horizontal
            
            collectionView?.bounces = false
            collectionView?.pagingEnabled = true
            collectionView?.showsHorizontalScrollIndicator = false
            
        }
    }
    
}

// MARK: - 设置布局
extension PhotoBrowserViewController {
    private func setupUI() {
        
        // 添加控件
        view.addSubview(collectionView)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        
        // 设置约束
        collectionView.frame = view.bounds
        
        closeButton.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(-8)
            make.left.equalTo(view.snp_left).offset(8)
            make.size.equalTo(CGSize(width: 100, height: 36))
        }
        
        saveButton.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(-8)
            make.right.equalTo(view.snp_right).offset(-28)
            make.size.equalTo(CGSize(width: 100, height: 36))
        }
        
        // MARK: - 添加按钮的监听方法
        closeButton.addTarget(self, action: "close", forControlEvents: .TouchUpInside)
        saveButton.addTarget(self, action: "save", forControlEvents: .TouchUpInside)
        
        // 准备collectionView
        prepareCollectionView()
    }
    
    // 准备collectionView
    private func prepareCollectionView() {
        // 注册可重用Cell
        collectionView.registerClass(PhotoBrowserCell.self, forCellWithReuseIdentifier: PhotoBrowserViewCellId)
        // 设置数据源方法
        collectionView.dataSource = self
        
    }
}


// MARK: - 实现collectionView 的数据源方法
extension PhotoBrowserViewController: UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urls.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoBrowserViewCellId, forIndexPath: indexPath) as! PhotoBrowserCell
        

        cell.imageURL = urls[indexPath.item]
        cell.PhotoDelegate = self
        
        return cell
        
    }
    
}

// MARK: - PhotoBrowserCellDelegate
extension PhotoBrowserViewController: PhotoBrowserCellDelegate {
    func PhotoBrowserCellDidTapImage() {
        imageViewForDismiss()
        close()
    }
}

// MARK: - 解除转场动画协议
extension PhotoBrowserViewController: PhotoBrowserDismissDelegate {
    func imageViewForDismiss() -> UIImageView {
        let iv = UIImageView()
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        let cell = collectionView.visibleCells()[0] as! PhotoBrowserCell
        iv.image = cell.imageView.image
        
        iv.frame = cell.scrollView.convertRect(cell.imageView.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
//        UIApplication.sharedApplication().keyWindow?.addSubview(iv)
        
        return iv
    }
    
    func indexPathForDismiss() -> NSIndexPath {
        return collectionView.indexPathsForVisibleItems()[0]
    }
}